<template>
  <a-card>
    <!-- <a-form-model ref="ruleForm" :model="form" :rules="rules" v-bind="layout"> -->
    <p style="text-align: center; font-size: 18px">产成品入库单</p>
    <br />

    <a-form-model
      class="ant-advanced-search-form"
      :model="form"
      v-bind="layout"
      ref="ruleForm"
      :rules="rules"
    >
      <a-row :gutter="24">
        <a-col :xl="8" :lg="12" :md="8" :sm="24" :xs="24">
          <a-form-model-item label="单据号" ref="document" prop="document">
            <a-input v-model="form.document" style="border: 0" disabled />
          </a-form-model-item>
        </a-col>
        <a-col :xl="8" :lg="12" :md="8" :sm="24" :xs="24">
          <a-form-model-item
            label="单据日期"
            ref="documentDate"
            prop="documentDate"
          >
            <a-date-picker
              v-model="form.documentDate"
              type="date"
              style="width: 100%"
              format="YYYY-MM-DD"
              @change="
                (a, b) => {
                  this.form.a = a;
                  this.form.documentDate = b;
                  this.form.balance = b;
                }
              "
            />
          </a-form-model-item>
        </a-col>

        <!-- 仓库搜索显示名称 -->
        <a-col :xl="8" :lg="12" :md="8" :sm="24" :xs="24">
          <a-form-model-item label="仓库名称" ref="depotName" prop="depotName">
            <a-select
              v-model="form.depotName"
              showSearch
              style="width: 100%"
              @change="formDepotNameSelectChange"
            >
              <!-- @change="
                  (val) => {
                    const arr = val.split('|');
                    this.form.depotName = arr[2];
                    this.form.depotId = arr[0];
                  }
                " -->
              <a-select-option
                v-for="item in storageList"
                :key="item.depotId"
                :value="
                  item.depotId + '|' + item.depotNo + '|' + item.depotName
                "
                >{{ item.depotNo }} {{ item.depotName }}</a-select-option
              >
            </a-select>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :xl="8" :lg="12" :md="8" :sm="24" :xs="24">
          <a-form-model-item
            label="收发类别"
            ref="sendReceiveType"
            prop="sendReceiveType"
          >
            <a-select
              placeholder=""
              showSearch
              v-model="form.sendReceiveType"
              @change="shoufaleibieMethod"
            >
              <a-select-option
                v-for="(item, index) in shoufaleibieList"
                :key="index"
                :value="item.id + '|' + item.name"
                >{{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :xl="8" :lg="12" :md="8" :sm="24" :xs="24">
          <a-form-model-item
            label="交货单位"
            ref="deliveryUnitName"
            prop="deliveryUnitName"
          >
            <a-tree-select
              v-model="form.deliveryUnitName"
              :replace-fields="replaceFields"
              style="width: 100%"
              allow-clear
              :tree-data="deliveryUnitList"
              showSearch
              @change="
                (value, b, extra) => {
                  this.form.deliveryUnitName = value;
                  this.form.b = b;
                  this.form.deliveryUnit = extra.triggerNode.eventKey;
                }
              "
            >
            </a-tree-select>
          </a-form-model-item>
        </a-col>
        <a-col :xl="8" :lg="12" :md="8" :sm="24" :xs="24">
          <a-form-model-item
            label="承包户"
            ref="contractorName"
            prop="contractorName"
          >
            <a-select
              showSearch
              style="width: 100%"
              v-model="form.contractorName"
              @change="
                (val) => {
                  const arr = val.split('|');
                  this.form.contractorName = arr[1];
                  this.form.contractor = arr[0];
                }
              "
            >
              <a-select-option
                v-for="item in contractorList"
                :key="item.value"
                :value="item.value + '|' + item.title"
                >{{ item.title }}</a-select-option
              >
            </a-select>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <!-- 承包户 -->

        <a-col :xl="8" :lg="12" :md="8" :sm="24" :xs="24">
          <a-form-model-item label="公司" ref="corp" prop="corp">
            <a-tree-select
              v-model="form.corp"
              show-search
              style="width: 100%"
              allow-clear
              :tree-data="CorpList"
              @change="getCorpId"
            >
            </a-tree-select>
          </a-form-model-item>
        </a-col>
        <a-col :xl="8" :lg="12" :md="8" :sm="24" :xs="24">
          <a-form-model-item label="库存组织" ref="bodyname" prop="bodyname">
            <a-select
              v-model="form.bodyname"
              @change="getpk_calbodyId"
              showSearch
              style="width: 100%"
            >
              <a-select-option
                v-for="item in InventoryOrganizationList"
                :key="item.id"
                :value="item.pkCalbody + '|' + item.bodyname"
              >
                {{ item.bodycode }}
                {{ item.bodyname }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :xl="8" :lg="12" :md="8" :sm="24" :xs="24">
          <a-form-model-item
            label="业务员"
            ref="salesmanName"
            prop="salesmanName"
          >
            <a-select
              @change="getsalesman"
              v-model="form.salesmanName"
              showSearch
              style="width: 100%"
              @search="searchUserInfoList"
            >
              <a-select-option
                v-for="item in UserList"
                :key="item.userId"
                :value="item.workNo + '|' + item.userName + '|' + item.userId"
              >
                {{ item.workNo }} {{ item.userName }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
      </a-row>

      <a-row>
        <a-col :span="24" :style="{ textAlign: 'right' }">
          <a-modal
            title="物品入库信息表"
            :visible="visible"
            :confirm-loading="confirmLoading"
            @ok="addgoods_Ok"
            @cancel="addgoods_Cancel"
          >
            <!-- 添加物品入库的模态框存放XX信息 -->
          </a-modal>
        </a-col>

        <!-- 生成原单按钮组件 -->

        <chanChengPinInpot
          :orderColumns="topColumns"
          :listColumns="listColumns"
          :ModalTitle="ModalTitle"
          :Modal="Modal"
          @origin-data="getOriginData"
          @origin-data2="getOriginData2"
        ></chanChengPinInpot>

        <a-table
          :columns="showgoods_columns"
          style="margin-top: 10px"
          :data-source="DataSource"
          :scroll="{ x: 4000, y: 670 }"
          :pagination="false"
          :locale="{ emptyText }"
        >
          <!-- 仓库 仓库编码 table cangkubianma-->
          <span slot="depotNo" slot-scope="text, record">
            <a-select
              v-model="record.depotNo"
              style="width: 100%"
              showSearch
              @change="setGoodsList(record.key)"
            >
              <a-select-option
                v-for="item in storageList"
                :key="item.depotNo"
                :value="item.depotNo + '|' + item.depotName"
              >
                {{ item.depotNo }} {{ item.depotName }}
              </a-select-option>
            </a-select>
          </span>

          <!-- 存货编码 cunhuobianma main table-->
          <span slot="inventoryName" slot-scope="text, record">
            <a-select
              v-model="record.inventoryName"
              style="width: 100%"
              @search="HandleSearch"
              @change="
                (val) => {
                  const arr = val.split('|');
                  record.inventoryId = arr[0];
                  record.inventoryNo = arr[1];
                  record.inventoryName_dictText = arr[2];
                  record.inventoryName = arr[2];
                  record.inventoryNo_dictText = arr[1];
                  record.specificationsModel_dictText = arr[3] || '';
                  record.specificationsModel = arr[3] || '';
                  record.unit = arr[4];
                }
              "
              showSearch
            >
              <a-select-option
                v-for="item in goodsList"
                :key="item.inventoryId"
                :value="
                  item.inventoryId +
                  '|' +
                  item.inventoryNo +
                  '|' +
                  item.inventoryName +
                  '|' +
                  item.standardModel +
                  '|' +
                  item.unit
                "
              >
                {{ item.inventoryNo }} {{ item.inventoryName }}
                {{ item.standardModel }}
              </a-select-option>
            </a-select>
          </span>

          <!-- 货架-->
          <span slot="shelves" slot-scope="text, record">
            <a @click="shelfDetails(record)">详情</a>
          </span>
          <!-- 仓位 -->
          <span slot="position" slot-scope="text, record">
            <a-tree-select
              v-model="record.position"
              style="width: 100%"
              :tree-data="record.positionList"
              allow-clear
            ></a-tree-select>
          </span>
          <!-- 冷库 -->
          <span slot="coldStorageId" slot-scope="text, record">
            <a-tree-select
              v-model="record.coldStorageId"
              style="width: 100%"
              :tree-data="record.coldStorageIdList"
              allow-clear
            ></a-tree-select>
          </span>
          <!-- 单价 -->
          <span slot="price" slot-scope="text, record">
            <a-input-number :precision="6" v-model="record.price" />
          </span>
          <!-- 数量 -->
          <span slot="quantity" slot-scope="text, record">
            <a-input-number
              :precision="3"
              :min="minnumber"
              :max="maxnumber"
              @change="changenumber(text, record)"
              v-model="record.quantity"
            />
          </span>

          <!-- 实收数量 -->
          <span slot="actualQuantityReceived" slot-scope="text, record">
            <a-input-number
              :precision="3"
              v-model="record.actualQuantityReceived"
              :min="minnumber"
              :max="maxnumber"
            />
          </span>
          <!-- 金额 -->
          <span slot="money" slot-scope="text, record">
            <a-input-number :precision="3" v-model="record.money" />
          </span>
          <!-- 棚号 -->
          <span slot="recordShedId" slot-scope="text, record">
            <a-input v-model="record.recordShedId" />
          </span>

          <!-- 生产日期-->
          <span slot="productionDate" slot-scope="text, record">
            <a-date-picker
              v-model="record.productionDate"
              @change="
                (a, b) => {
                  record.a = a;
                  record.productionDate = b;
                }
              "
            />
          </span>
          <!-- 保质期(月) -->
          <span slot="shelfLife" slot-scope="text, record">
            <a-input v-model="record.shelfLife" />
          </span>
          <!-- 入库日期 -->
          <span slot="inputDate" slot-scope="text, record">
            <a-date-picker
              v-model="record.inputDate"
              @change="
                (a, b) => {
                  record.a = a;
                  record.inputDate = b;
                }
              "
            />
          </span>
          <!-- 备注 -->
          <span slot="remark" slot-scope="text, record">
            <a-input v-model="record.remark" />
          </span>

          <template slot="action" slot-scope="text, record">
            <span>
              <a @click="getGoodsShelves(record.key)">选择货架</a>
            </span>
            |
            <span>
              <a @click="cancle(record.key)">取消</a>
            </span>
          </template>
        </a-table>
      </a-row>

      <SelectShelf
        :goodsShelvesTag="goodsShelvesTag"
        :tableKey="tableKey"
        ref="goodShelvesInfo"
        @get-goodShelveInfo="getGoodShelveInfo"
        @close-goodShelveInfo="closegoodShelveInfo"
      >
      </SelectShelf>

      <!-- 添加一条信息 -->
      <a-button
        style="width: 100%; margin-top: 16px; margin-bottom: 8px"
        type="dashed"
        icon="plus"
        @click="newMember"
        v-if="!edit"
        >添加</a-button
      >
      合计物品数量:{{ this.mountall }}
      <div style="margin-top: 20px">
        <!-- 单据 -->

        <a-row>
          <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-model-item
              label="负责人"
              ref="responsiblePersonName"
              prop="responsiblePersonName"
            >
              <a-select
                v-model="form.responsiblePersonName"
                style="width: 100%"
                showSearch
                @change="
                  (val) => {
                    const arr = val.split('|');
                    this.form.responsiblePersonName = arr[2];
                    this.form.responsiblePerson = arr[0];
                  }
                "
              >
                <a-select-option
                  v-for="item in responsiblePersonList"
                  :key="item.userId"
                  :value="item.userId + '|' + item.workNo + '|' + item.userName"
                >
                  {{ item.workNo }} {{ item.userName }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>

          <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-model-item
              label="审核人"
              ref="inspectorName"
              prop="inspectorName"
            >
              <a-select
                v-model="form.inspectorName"
                showSearch
                style="width: 100%"
                @change="
                  (val) => {
                    const arr = val.split('|');
                    this.form.inspectorName = arr[2];
                    this.form.inspector = arr[0];
                  }
                "
              >
                <a-select-option
                  v-for="item in inspectorList"
                  :key="item.userId"
                  :value="item.userId + '|' + item.workNo + '|' + item.userName"
                >
                  {{ item.workNo }} {{ item.userName }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>

          <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-model-item label="审核日期" ref="balance" prop="balance">
              <a-date-picker
                v-model="form.balance"
                type="date"
                style="width: 100%"
                disabled
              />
            </a-form-model-item>
          </a-col>

          <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-model-item
              label="制单人"
              ref="singleProducerName"
              prop="singleProducerName"
            >
              <a-input disabled v-model="form.singleProducerName"> </a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
      </div>
    </a-form-model>

    <!-- 提交按钮组  -->
    <div style="margin-top: 20px">
      <center>
        <!-- <a-button type="primary" style="margin-right: 20px"> 打印 </a-button> -->
        <a-button
          @click="handleSaveButton"
          style="margin-right: 20px"
          :disabled="isAntiAudit"
        >
          保存
        </a-button>
        <a-button
          @click="Auditfunction"
          style="margin-right: 20px"
          :disabled="!isAntiAudit"
        >
          审核
        </a-button>

        <!-- <a-button
            type="primary"
            @click="Submit"
            style="margin-right: 20px"
            :disabled="!alreadyRecordTag"
          >
            提交
          </a-button> -->
      </center>
    </div>

    <a-modal
      title="货架详情"
      :visible="shelfWindow"
      @ok="handleOk_shelfDetails"
      width="50%"
      @cancel="handleCancel_shelfDetails"
    >
      {{ this.saveShelfDetails }}
    </a-modal>
  </a-card>
</template>

<script>
// ------- 公共接口 ------- ;
import SelectShelf from "../../components/common/SelectShelf"; //货架

import { ChanChengPinRuKuHttp } from "@/services/modules/RuKuGuGuanLi/ChanChengPinRuKu";
const cprkHttp = new ChanChengPinRuKuHttp(); // 采购入库

import { CommonAjax } from "@/services/modules/common";
const comHttp = new CommonAjax(); // 公用接口
// ------- 根据源单生成组件 ------- ;
// import stockManagement from "../../components/common/stockManagement";
import chanChengPinInpot from "../../components/common/chanChengPinInpot";
import moment from "moment";
import { mapState, mapGetters } from "vuex";

// import func from 'vue-editor-bridge';
// 这里是搜索后显示到的信息列

//通知提醒key值
// const key = "updatable";

const showgoods_columns = [
  {
    title: "序号",
    align: "center",
    width: "80px",
    dataIndex: "key",
    key: "key",
  },
  {
    title: "仓库编码",
    dataIndex: "depotNo",
    key: "depotNo",
    align: "center",
    width: "10%",
    scopedSlots: { customRender: "depotNo" },
  },
  {
    title: "仓库名称",
    dataIndex: "depotName",
    key: "depotName",
    align: "center",
    width: "5%",
    scopedSlots: { customRender: "depotName" },
  },
  {
    title: "冷库号",
    dataIndex: "coldStorageId",
    key: "coldStorageId",
    align: "center",
    width: "5%",
    scopedSlots: { customRender: "coldStorageId" },
  },
  {
    title: "仓位",
    dataIndex: "position",
    key: "position",
    align: "center",
    width: "5%",
    scopedSlots: { customRender: "position" },
  },

  {
    title: "存货编码",
    dataIndex: "inventoryNo",
    key: "inventoryNo",
    align: "center",

    // scopedSlots: { customRender: "inventoryNo_dictText" },
  },
  {
    title: "存货名称",
    dataIndex: "inventoryName",
    key: "inventoryName",
    align: "center",
    width: "15%",
    scopedSlots: { customRender: "inventoryName" },
  },
  {
    title: "规格型号",
    dataIndex: "specificationsModel",
    key: "specificationsModel",
    align: "center",
    // scopedSlots: { customRender: "specificationsModel" },
  },

  {
    title: "单位",
    dataIndex: "unit",
    key: "unit",
    align: "center",
    scopedSlots: { customRender: "unit" },
  },
  {
    title: "单价", // ! 目前没有
    dataIndex: "price",
    key: "price",
    align: "center",
    scopedSlots: { customRender: "price" },
  },
  {
    title: "数量",
    dataIndex: "quantity",
    key: "quantity",
    align: "center",
    scopedSlots: { customRender: "quantity" },
  },
  {
    title: "实收数量",
    dataIndex: "actualQuantityReceived",
    key: "actualQuantityReceived",
    align: "center",
    width: "5%",
    scopedSlots: { customRender: "actualQuantityReceived" },
  },
  {
    title: "金额", // ! 目前没有
    dataIndex: "money",
    key: "money",
    align: "center",
    scopedSlots: { customRender: "money" },
  },
  {
    title: "棚号",
    dataIndex: "recordShedId_dictText",
    key: "recordShedId_dictText",
    width: "5%",
    align: "center",
    scopedSlots: { customRender: "recordShedId_dictText" },
  },

  {
    title: "源单号",
    dataIndex: "documentNo",
    key: "documentNo",
    align: "center",
    scopedSlots: { customRender: "documentNo" },
  },
  {
    title: "生产日期",
    dataIndex: "productionDate",
    key: "productionDate",
    align: "center",
    width: "5%",
    scopedSlots: { customRender: "productionDate" },
  },
  {
    title: "保质期(月)",
    dataIndex: "shelfLife",
    key: "shelfLife",
    align: "center",
    width: "5%",
    scopedSlots: { customRender: "shelfLife" },
  },
  // {
  //   title: "批次号",
  //   dataIndex: "batchNumber",
  //   key: "batchNumber",
  //   align: "center",
  //   width: "5%",

  //   scopedSlots: { customRender: "batchNumber" },
  // },
  {
    title: "货架",
    dataIndex: "shelves",
    key: "shelves",
    align: "center",
    width: "5%",
    scopedSlots: { customRender: "shelves" },
  },
  {
    title: "入库日期", // 默认今天
    dataIndex: "inputDate",
    key: "inputDate",
    align: "center",
    width: "5%",

    scopedSlots: { customRender: "inputDate" },
  },
  {
    title: "备注",
    dataIndex: "remark",
    key: "remark",
    align: "center",
    scopedSlots: { customRender: "remark" },
  },
  {
    title: "操作",
    dataIndex: "action",
    key: "action",
    align: "center",
    fixed: "right",
    scopedSlots: { customRender: "action" },
  },
];
// ------- 根据源单生成   上表 ------- ;
const topColumns = [
  {
    // title: "货物名称",
    title: "序号",
    dataIndex: "key",
    key: "key",
    width: "80px",

    // fixed: "left",
  },
  {
    title: "结转单号",
    dataIndex: "documentNo",
    key: "documentNo",
    align: "center",
    scopedSlots: { customRender: "documentNo" },
  },
  {
    title: "交货单位",
    dataIndex: "deliveryUnit_dictText",
    key: "deliveryUnit_dictText",
    align: "center",
    scopedSlots: { customRender: "deliveryUnit_dictText" },
  },
  {
    title: "结转日期",
    dataIndex: "carryoverDate",
    key: "carryoverDate",
    align: "center",
    scopedSlots: { customRender: "carryoverDate" },
  },
  {
    title: "审核标志",

    dataIndex: "documentClosed",
    align: "center",
    scopedSlots: { customRender: "documentClosed" },
  },
];
// ------- 根据源单生成  下表 ------- ;
const listColumns = [
  {
    title: "存货编码",
    dataIndex: "inventoryNo_dictText",
    key: "inventoryNo_dictText",
    align: "center",
    scopedSlots: { customRender: "inventoryNo_dictText" },
  },
  {
    title: "存货名称",
    dataIndex: "inventoryNoViaName_dictText",
    key: "inventoryNoViaName_dictText",
    align: "center",
    scopedSlots: { customRender: "inventoryNoViaName_dictText" },
  },
  {
    title: "规格",
    dataIndex: "specification",
    key: "specification",
    align: "center",
    scopedSlots: { customRender: "specification" },
  },
  {
    title: "棚号",
    dataIndex: "recordShedNumber",
    key: "recordShedNumber",
    align: "center",
    scopedSlots: { customRender: "recordShedNumber" },
  },
  {
    title: "剩余数量",
    dataIndex: "remainingQuantity",
    key: "remainingQuantity",
    align: "center",
    scopedSlots: { customRender: "remainingQuantity" },
  },
  {
    title: "转出数量",
    dataIndex: "transferOutQuantity",
    key: "transferOutQuantity",
    align: "center",
    scopedSlots: { customRender: "transferOutQuantity" },
  },
  {
    title: "生产日期",
    dataIndex: "productionDate",
    key: "productionDate",
    align: "center",
    scopedSlots: { customRender: "productionDate" },
  },
  {
    title: "审核标志",
    dataIndex: "documentClosed",
    align: "center",
    scopedSlots: { customRender: "documentClosed" },
  },
];
// 添加物品入库信息的数据表单
const addgoods_data = [
  {
    title: "存货编码",
    dataIndex: "inventoryNo",
    key: "inventoryNo",
    align: "center",
    width: "5%",

    scopedSlots: { customRender: "inventoryNo" },
  },
  {
    title: "存货名称",
    dataIndex: "inventoryName",
    key: "inventoryName",
    align: "center",
    scopedSlots: { customRender: "inventoryName" },
  },
  {
    title: "规格型号",
    dataIndex: "standardModel",
    key: "standardModel",
    align: "center",
    scopedSlots: { customRender: "standardModel" },
  },

  {
    title: "单位",
    dataIndex: "unit",
    key: "unit",
    align: "center",
    scopedSlots: { customRender: "unit" },
  },
  {
    title: "单价",
    dataIndex: "price",
    key: "price",
    align: "center",
    scopedSlots: { customRender: "price" },
  },
  {
    title: "数量",
    dataIndex: "quantity",
    key: "quantity",
    align: "center",
    scopedSlots: { customRender: "quantity" },
  },
  // { title: "金额", width: 100, dataIndex: "money", key: "8" },
  {
    title: "扣重",
    dataIndex: "weightLoss",
    key: "weightLoss",
    align: "center",
    scopedSlots: { customRender: "weightLoss" },
  },
  {
    title: "仓库编码",
    dataIndex: "depotNo",
    key: "depotNo",
    align: "center",
    width: "5%",

    scopedSlots: { customRender: "depotNo" },
  },
  {
    title: "仓库名称",
    dataIndex: "depotName",
    key: "depotName",
    align: "center",
    width: "5%",

    scopedSlots: { customRender: "depotName" },
  },
  {
    title: "仓位",
    dataIndex: "position",
    key: "position",
    align: "center",
    scopedSlots: { customRender: "position" },
  },
  {
    title: "冷库号",
    dataIndex: "coldStorageId",
    key: "coldStorageId",
    align: "center",
    scopedSlots: { customRender: "coldStorageId" },
  },
  {
    title: "源单号",
    dataIndex: "sourceNumber",
    key: "sourceNumber",
    align: "center",
    scopedSlots: { customRender: "sourceNumber" },
  },
  {
    title: "生产日期",
    dataIndex: "productDate",
    key: "productDate",
    align: "center",
    width: "5%",

    scopedSlots: { customRender: "productDate" },
  },
  {
    title: "保质期(月)",
    dataIndex: "expirationTime",
    key: "expirationTime",
    align: "center",
    scopedSlots: { customRender: "expirationTime" },
  },
  {
    title: "批次号",
    dataIndex: "batchNumber",
    key: "batchNumber",
    align: "center",
    scopedSlots: { customRender: "batchNumber" },
  },
  {
    title: "入库日期",
    dataIndex: "inputDate",
    key: "inputDate",
    align: "center",
    width: "5%",

    scopedSlots: { customRender: "inputDate" },
  },
  {
    title: "备注",
    dataIndex: "remark",
    key: "remark",
    align: "center",
    scopedSlots: { customRender: "remark" },
  },
];
export default {
  //组件
  components: {
    chanChengPinInpot,
    SelectShelf,
  },
  ...mapState("user", { currUser: "info", currPost: "position" }),
  ...mapGetters({
    getDepsInfo: "user/getDepsInfo",
  }),
  data() {
    // this.cacheData = data.map((item) => ({ ...item }));

    return {
      IsNotEmpty: true, //提交时是否否和全部必填条件，是返回true

      replaceFields: {
        children: "syncDepartmentFilesEntityList",
        title: "deptname",
        value: "pkDeptdoc",
      },

      //暂无数据默认值
      emptyText: "选择源单生成",
      shelfWindow: false,

      //货架详情
      saveShelfDetails: "",

      //货架选择子组件
      goodsShelvesTag: false,
      tableKey: 0,
      shelvesArray: [],
      //----- 申请的表单内容信息 -----
      form: {
        document: "", // 单据号
        documentDate: moment().format("YYYY-MM-DD"), // 单据日期
        depotId: "", // 仓库名称
        depotName: "",
        // storageUnit: "", // 所属单位
        storageUnitName: "",
        sendReceiveType: "", // 收发类别
        sendReceiveTypeName: "",
        deliveryUnit: "", // 交货单位
        deliveryUnitName: "",
        contractorName: "", // 承包户
        contractor: "",
        responsiblePerson: "", // 负责人
        responsiblePersonName: "",
        inspectorName: "", // 审核人
        inspector: "",
        balance: moment().format("YYYY-MM-DD"), // 审核日期
        singleProducerName: this.$store.state.user.info.username, // 制单人
        singleProducer: this.$store.state.user.info.id, // 制单人Id

        corp: "",
        corpId: "",
        pkCalbody: "1001F3100000000002LS", //!库存组织名称id
        bodyname: "", //库存组织名称
        salesman: "", //!业务员id
        cbizid: "", //!业务员id 这里两个都传,传一样的
        salesmanName: "", //业务员name
      },
      CorpList: [], //公司列表
      InventoryOrganizationList: [], // 库存组织列表
      UserList: [], // 库管员列表
      topColumns,
      listColumns,
      showgoods_columns, // 入库信息显示列名
      addgoods_data, //  入库信息添加字段
      workNoList: [], // 判重使用
      editingKey: "",
      selectedRowKeys: [],
      //页面布局

      layout: {
        labelCol: { span: 6, offset: 1 },
        wrapperCol: { span: 15, offset: 1 },
      },
      layoutButton: {
        labelCol: { span: 4, offset: 10 },
        wrapperCol: { span: 14, offset: 17 },
      },
      detailLayout: {
        labelCol: { span: 8 },
        wrapperCol: { span: 15 },
      },

      ModalTitle: "结转单生成产成品入库单",
      Modal: "源单",
      alreadyCheckTag: false, // 没审核
      alreadyRecordTag: false, // 记账标志

      qualityVisible: false, //质检单显示属性
      ExamineDisplay: true, // 审核、提交按钮是否显示

      visible: false,
      confirmLoading: false,
      SearchVisible: false, //源单号详情请页面显示类型
      EntryVisible: false, //采购订单生成采购入库单
      qualityData: [], //质检单数据来源
      DataSource: [], //入库单数据来源
      rukudan_data: [], //入库单数据来源
      // ------- 字典表数据 ------- ;
      giveAwayList: [], // 是否赠品列表
      positionList: [], // 仓位列表
      coldStorageIdList: [], //冷库号
      shoufaleibieList: [], //收发类别列表
      storageList: [], //仓库名称列表
      department: [], // 部门列表
      inspectorList: [], // 审核人列表
      inspectorIdList: [], // 审核人Id列表
      // batchNumberList: [], // 批次号
      responsiblePersonList: [], // 负责人列表
      surveyorList: [], //检验人列表
      contractorList: [], //承包户列表
      deliveryUnitList: [], //交货单位列表

      //应该从采购系统接口获取数据
      supplierList: [], //供货商列表

      UpdateTmp: true, // 修改标志
      editOrAdd: "", // 编辑 还是 新增
      edit: false, // 是否可以编辑
      goodsList: [],
      // shelvesList: [], //货架信息

      empty_: true,

      //数量输入框默认最小值是1
      minnumber: 0,
      maxnumber: Infinity,
      isAntiAudit: false,
      mountall: 0,

      // 新增验证规则
      rules: {
        inventoryName: [
          { required: true, message: "请填写存货信息！", trigger: "blur" },
        ],
        document: [
          { required: true, message: "单据号为必填项！", trigger: "blur" },
        ],

        documentDate: [
          { required: true, message: "单据日期为必填项！", trigger: "blur" },
        ],

        depotName: [
          { required: true, message: "仓库名称为必填项！", trigger: "blur" },
        ],
        // storageUnitName: [
        //   { required: true, message: "所属单位为必填项！", trigger: "blur" },
        // ],
        sendReceiveType: [
          { required: true, message: "收发类别为必填项！", trigger: "blur" },
        ],

        deliveryUnitName: [
          { required: true, message: "交货单位为必填项！", trigger: "change" },
        ],
        // contractorName: [
        //   { required: true, message: "承包户为必填项！", trigger: "blur" },
        // ],
        corp: [
          { required: true, message: "公司为必填项！", trigger: "change" },
        ],
        bodyname: [
          { required: true, message: "库存组织为必填项！", trigger: "blur" },
        ],
        // salesmanName: [
        //   { required: true, message: "业务员为必填项！", trigger: "blur" },
        // ],
        // responsiblePersonName: [
        //   { required: true, message: "负责人为必填项！", trigger: "blur" },
        // ],
        inspectorName: [
          { required: true, message: "审核人为必填项！", trigger: "blur" },
        ],
        // balance: [
        //   { required: true, message: "审核日期为必填项！", trigger: "blur" },
        // ],
        singleProducerName: [
          { required: true, message: "制单人为必填项！", trigger: "blur" },
        ],
      },
    };
  },
  computed: {
    // ------- 多选函数 ------- ;
    rowSelection() {
      const { selectedRowKeys } = this;
      return {
        selectedRowKeys,
        onChange: this.onSelectChange,
        hideDefaultSelections: true,
        onSelection: this.onSelection,
      };
    },
    // ------- 页面布局 ------- ;
    formItemLayout() {
      const { formLayout } = this;
      return formLayout === "horizontal"
        ? {
            labelCol: { span: 4 },
            wrapperCol: { span: 14 },
          }
        : {};
    },
  },

  watch: {
    $route: function (to, form) {
      console.log(to, form);
      if (to.query.document) {
        console.log("--------- 更新视图 产成品入库  ----------");
        console.log("this.$route.query.document", this.$route.query.document);
        if (this.$route.query.document) {
          this.getMainListByDocmentToEdit();
        }
      } else {
        console.log("更新");
        this.InitOriginData();
      }
      
      // if (to.path == "/ProductInput" && form.path == "/ProductInputList") {

      // }
    },
  },

  //生命周期函数
  mounted() {
    this.judgeDocument(); //判断单据号是否为空
    this.getDeparmentTree(); //获取交货单位
    this.getContractorList(); //获取承包户列表
    this.shoufaleibieListmethod(); //收发类别列表
    this.getOriginalNumber(); // 生成源单号
    // this.setColumns(); // 生成多条数据
    this.getApplyOrder(); // 获取单据号
    this.getApplyStorage(); // 获取仓库
    this.getGiveawayList(); // 是否赠品列表
    this.getResponsiblePersonList(); // 获取负责人列表
    this.getInspectorList(); // 获取审核人
    this.getTodayBatchNumber(); // 获取当天批次号
    this.getCorpInfo(); //获取公司
    this.getSyncInventoryOrganizationList(); //获取库存组织列表
    // this.getSelectShelvesByShedId(); //获取货架
    // 判断修改
    console.log(
      "this.mounted,$route.query.document",
      this.$route.query.document
    );
    if (this.$route.query.document) {
      this.getMainListByDocmentToEdit();
    }
  },
  //监听

  methods: {
    // ————判断单据号是否为空————
    judgeDocument() {
      setTimeout(() => {
        if (this.form.document === "") {
          this.$message.error("未获取到单据号,请刷新页面重试");
        }
      }, 3000);
    },
    /**
    //todo @description: 查看货架详情
    * @description: ...
    * @return
    */
    shelfDetails(record) {
      this.shelfWindow = true;
      this.saveShelfDetails = record.shelves;
    },
    handleOk_shelfDetails() {
      this.shelfWindow = false;
      this.saveShelfDetails = "";
    },
    handleCancel_shelfDetails() {
      this.shelfWindow = false;
      this.saveShelfDetails = "";
    },
    /**
    //todo @description: 选择货架功能
    * @description: ...
    * @return
    */
    getGoodsShelves(key) {
      this.goodsShelvesTag = true;
      this.tableKey = key;
      setTimeout(() => {
        this.$refs.goodShelvesInfo.getGoodShelveInfo();
      }, 0);
    },
    //todo 点击确定
    getGoodShelveInfo(key, goodsShelvesList) {
      console.log("序号和货架列表", key, goodsShelvesList);
      let str = "";
      goodsShelvesList.forEach((element) => {
        str = str + element.shelvesCode + ",";
      });
      str = str.substring(0, str.length - 1);
      this.$set(this.DataSource[key - 1], "shelves", str);
      this.goodsShelvesTag = false;
    },
    //todo 点击取消
    closegoodShelveInfo() {
      this.goodsShelvesTag = false;
    },

    // //获取货架信息
    // getSelectShelvesByShedId() {
    //   cprkHttp.getSelectShelvesByShedId().then((res) => {
    //     console.log("获取货架信息", res);
    //     this.shelvesList = res.result;
    //   });
    // },
    // changeshelves(value) {
    //   console.log(value);
    //   console.log(this.DataSource, "this.datasourceS");
    // },

    // 业务员列表
    getsalesman(data) {
      let array = data.split("|");
      this.form.salesman = array[2];
      this.form.salesmanName = array[1];
      this.form.cbizid = array[2];
      // console.log("this.Form.cbizid ", this.form.cbizid);
      // console.log("this.Form.salesman ", this.form.salesman);
    },
    //公司change函数
    getCorpId(value) {
      let array = value.split("|");
      this.form.corpId = array[0];
    },
    //获取公司
    getCorpInfo() {
      comHttp.getpk_corpList().then((res) => {
        // console.log("获取公司信息", res);
        this.CorpList = res.result;
        this.changeCorpData(this.CorpList);
      });
    },
    //公司的数据拼凑
    changeCorpData(Tree) {
      Tree.forEach((element) => {
        element["title"] = element.unitcode + " " + element.unitname;
        element["value"] = element.pkCorp + "|" + element.unitname;
        element["children"] = element.syncCompanyEntityList;
        element["key"] = element.id;
        if (element.children) {
          this.changeCorpData(element.children);
        }
      });
    },
    getpk_calbodyId(value) {
      // console.log("value", value);
      let array = value.split("|");
      this.form.pkCalbody = array[0];
      // console.log("this.Form.pkCalbody", this.form.pkCalbody);
    },
    getSyncInventoryOrganizationList() {
      comHttp.getSyncInventoryOrganizationList().then((res) => {
        // console.log("库存组织", res);
        this.InventoryOrganizationList = res.result;
      });
    },
    searchUserInfoList(value) {
      // this.UserList = [];
      if (value != "") {
        let queryPath = "?username=" + value;
        comHttp.getUserInfoByUserName(queryPath).then((res) => {
          for (let i = 0; i < res.result.list.length; i++) {
            if (!this.workNoList.includes(res.result.list[i].workNo)) {
              let data = {
                userName: res.result.list[i].username,
                userId: res.result.list[i].id,
                workNo: res.result.list[i].workNo,
              };
              this.UserList.push(data);
              this.workNoList.push(res.result.list[i].workNo);
            }
          }
        });
      }
    },
    changenumber(data, record) {
      console.log(record, "record");
      console.log("data", data);
      //todo 合计物品数量合计
      this.mountall = 0;
      for (let i = 0; i < this.DataSource.length; i++) {
        this.mountall += this.DataSource[i].quantity;
      }
    },
    //延迟
    debounce(value, wait) {
      if (this.timeout) clearTimeout(this.timeout);
      this.timeout = setTimeout(() => {
        this.onfunc(value);
      }, wait);
    },

    HandleSearch(value) {
      this.debounce(value, 500);
    },
    async onfunc(value) {
      var goodsList_invname = [];
      var goodsList_invspec = [];
      //模糊查询
      this.goodsList = [];
      console.log("value", value);
      let query = "?name=" + value;
      if (value == "" || value == null) {
        this.goodsList = [];
      } else {
        await comHttp
          .getgetSearchInventoryInformationFile(query)
          .then((res) => {
            // console.log("结果为", res);
            // this.goodsList = res.result;
            for (let i = 0; i < res.result.length; i++) {
              if (
                res.result[i].standardModel == "null" ||
                res.result[i].standardModel == null
              ) {
                res.result[i].standardModel = "";
              }
              if (res.result[i].unit == "null" || res.result[i].unit == null) {
                res.result[i].unit = "";
              }
              let data = {
                inventoryId: res.result[i].pkInvbasdoc, // 存货 id
                inventoryNo: res.result[i].invcode, //存货编码
                inventoryName: res.result[i].invname, //存货名称
                standardModel: res.result[i].invspec, //规格型号
                unit: res.result[i].measname, //单位
              };
              // console.log("data-----:",JSON.stringify(data));
              goodsList_invname.push(data);
            }
          });

        let queryInventoryBySpec = "?invspec=" + value;
        //规格型号模糊查询
        await comHttp
          .getqueryInventoryBySpec(queryInventoryBySpec)
          .then((res) => {
            // console.log("结果规格型号模糊查询", res);

            for (let i = 0; i < res.result.list.length; i++) {
              let data = {
                inventoryId: res.result.list[i].pkInvbasdoc, // 存货 id
                inventoryNo: res.result.list[i].invcode, //存货编码
                inventoryName: res.result.list[i].invname, //存货名称
                standardModel: res.result.list[i].invspec, //规格型号
                unit: res.result.list[i].measname, //单位
              };
              goodsList_invspec.push(data);
            }
          });
        //todo 合并去重函数
        await this.mergeArray(goodsList_invname, goodsList_invspec);
        //等待控制
        // this.Waiting = false;
      }
    },
    //todo 合并去重函数
    mergeArray(arr1, arr2) {
      let arrs = [...arr1, ...arr2];
      //根据inventoryId去重
      let map = new Map();
      for (let item of arrs) {
        if (!map.has(item.inventoryId)) {
          map.set(item.inventoryId, item);
        }
      }
      this.goodsList = [...map.values()]; //将
    },
    getMainListByDocmentToEdit() {
      if (this.$route.query.isAntiAudit == "已反审核") {
        this.isAntiAudit = true;
      }
      this.editOrAdd = "edit";
      this.edit = true; // 进行修改
      let _query = "";
      const document = this.$route.query.document;
      const auditMark = this.$route.query.auditMark;
      const singleProducer = this.$route.query.singleProducer;
      _query += "?pageSize=500&inOutIdentification=1"; // 内容数量 入库
      _query += "&inOutCategoryIdentification=2";
      _query += `&auditMark=${auditMark}`; // 未审核:2 审核：1
      _query += `&document=${document}`; // 单据号
      _query += `&singleProducer=${singleProducer}`; // 制单人
      comHttp.getInOrOutStorageOrderAndGoodsList(_query).then((res) => {
        if (res.result.records.length < 1) {
          this.$message.error("[ERROR] 没有查询到此条数据");
          return;
        }
        let _data = res.result.records;
        let firstData = _data[0];

        this.form.id = firstData.id;

        this.form.document = firstData.document; // 单据号
        this.form.documentDate = firstData.documentDate; // 单据日期

        this.form.depotName = firstData.storname; // 仓库名称
        // this.form.depotName = firstData.depotId_dictText;

        //公司
        this.form.corp = firstData.pkCorp + firstData.pkCorp_dictText;
        this.form.corpId = firstData.pkCorp;
        //业务员
        this.form.salesmanName = firstData.cbizid_dictText;
        this.form.salesman = firstData.cbizid;
        this.form.bodyname = firstData.pkCalbody_dictText; // 库存组织
        this.form.pkCalbody = firstData.pkCalbody; // 库存组织

        // this.form.StorageUnit = firstData.StorageUnit; // 所属单位
        // this.form.storageUnitName = firstData.storageUnit_dictText; // 所属单位

        this.form.sendReceiveType = firstData.sendReceiveType_dictText;
        this.form.sendReceiveTypeId = firstData.sendReceiveType;

        this.form.deliveryUnit = firstData.deliveryUnit; // 交货单位
        this.form.deliveryUnitName = firstData.deliveryUnit_dictText;

        this.form.contractorName = firstData.contractor_dictText; // 承包户
        this.form.contractor = firstData.contractor;

        // -- -- -- -- -- -- -- -- -- -- //

        // 负责人
        this.form.responsiblePerson = firstData.responsiblePerson;
        this.form.responsiblePersonName = firstData.responsiblePerson_dictText;

        // 检验人
        // this.form.surveyorId = firstData.inspector;
        // this.form.inspector = firstData.inspector;
        // this.form.surveyor = firstData.inspector_dictText;

        // 检验日期
        this.form.balance = firstData.balance;

        this.form.inspectorName = firstData.inspector_dictText; // 审核人
        this.form.inspector = firstData.inspector;

        let options = _data.map((item, index) => {
          return {
            key: index + 1,
            documentNo: item.sourceNumber, //源单号
            // auxiliaryUnit: 0, // 辅助单位 现在暂时没有
            batchNumber: item.batchNumber, // 批次号
            shelves: item.remarkShelf, //货架
            depotId: item.pkStordoc, // 仓库编码（库存组织外键）
            depotNo: item.storcode, // 仓库编码（库存组织外键）
            depotName: item.storname, // 仓库编码（库存组织外键）
            // ? ? id: 0,
            money: item.money, // 金额
            position: item.position_dictText, // 仓位
            coldStorageId: item.coldStorageId_dictText, // 冷库号
            depotLocation: item.depotLocation_dictText, // 库位
            recordShedId_dictText: item.shedNo, // 棚号
            productionDate: item.productionDate, // 生产日期
            quantity: item.quantity, // 数量
            remark: item.remark, // 备注
            shelfLife: item.shelfLife, // 保质期
            sourceNumber: item.sourceNumber, // 源单单号（外键）
            inputDate: item.storageDate, // 入库日期
            inventoryNo: item.invcode, // 存货编码
            inventoryName: item.invname, // 存货编码
            inventoryId: item.inventoryId, // 存货编码（存货信息档案外键）
            specificationsModel_dictText: item.specificationsModel, // 规格型号
            unit: item.measname, // 单位
            price: item.unitPrice, // 单价
            twoId: item.twoId, // 数组内传递的id
          };
        });
        this.DataSource = options;
      });
    },
    InitOriginData() {
      this.form = {
        document: "", // 单据号
        documentDate: moment().format("YYYY-MM-DD"), // 单据日期
        depotId: "", // 仓库名称
        depotName: "",
        // storageUnit: "", // 所属单位
        // storageUnitName: "",
        sendReceiveType: "", // 收发类别
        sendReceiveTypeName: "",
        deliveryUnit: "", // 交货单位
        deliveryUnitName: "",
        contractorName: "", // 承包户
        contractor: "",
        responsiblePerson: "", // 负责人
        responsiblePersonName: "",
        inspectorName: "", // 审核人
        inspector: "",
        balance: moment().format("YYYY-MM-DD"), // 审核日期
        singleProducerName: this.$store.state.user.info.username, // 制单人
        singleProducer: this.$store.state.user.info.id, // 制单人Id
      };
      this.DataSource = []; //tanble重置
      this.mountall = 0; //合计物品数量重置
      this.getApplyOrder(); // 获取单据号
    },

    // @change="
    //   (val) => {
    //     const arr = val.split('|');
    //     this.form.storageUnitName = arr[2];
    //     this.form.storageUnit = arr[0];
    //   }
    // "
    //  --- 批量设置 所属单位   --- //
    formStorageUnitSelectChange(value) {
      // console.log("value", value);

      let arr = value.split("|");
      console.log("arr", arr);
      this.form.storageUnitName = arr[2];
      this.form.storageUnit = arr[0];

      for (let i = 0; i < this.DataSource.length; i++) {
        this.DataSource[i].storageUnit = arr[0];
        this.DataSource[i].storageUnitName = arr[2];
        this.DataSource[i].batchNumber = this.todayBatchNumber;
      }
    },
    // 仓库名称
    formDepotNameSelectChange(value) {
      let array = value.split("|");

      // 获取物品信息列表,根据仓库编码
      // let goodsList = this.getGoodSInfo(array[0]);

      // 根据仓库查询物品信息,并存储到相应的物品信息表中
      for (let i = 0; i < this.DataSource.length; i++) {
        this.DataSource[i].depotId = array[0];
        this.DataSource[i].depotNo = array[1];
        this.DataSource[i].depotName = array[2];
        this.DataSource[i].batchNumber = this.todayBatchNumber;
        // ---                                      ---//
        this.getGoodSInfo2(this.DataSource[i], array[0]);
        this.getPositionListById(this.DataSource[i], array[0]); // 获取仓位信息
      }
      console.log("仓库获取:::::", this.DataSource);
    },

    // 获取部门列表
    getDeparmentTree() {
      // console.log("获取部门列表hanshu===");
      comHttp.getDepartmentList().then((res) => {
        if (res.success) {
          console.log("获取部门树", res);
          let resetRes = res.result;
          this.resetDepartmentTree(resetRes);
          this.deliveryUnitList = resetRes;
          // console.log("this.depTree", this.depTree);
        }
      });
    },
    // 部门字典表中每一项vlaue 变成 title 为了方便搜索
    resetDepartmentTree(dep) {
      dep.forEach((item) => {
        // console.log("item", item);
        item.value = item.title;
        if (item.children) {
          this.resetDepartmentTree(item.children);
        }
      });
    },
    //获取承包户列表
    getContractorList() {
      this.contractorList = [];
      cprkHttp.getContractorList().then((res) => {
        console.log("----- 承包户列表 -----", res);
        res.result.list.forEach((element) => {
          let data = {
            title: element.name,
            value: element.id,
          };
          this.contractorList.push(data);
        });
      });
    },

    // //获取供应商列表
    // getSupplierList() {
    //   this.supplierList = [];
    //   cprkHttp.getSupplierList().then((res) => {
    //     console.log("----- 供应商列表信息 -----", res);
    //     for (let i = 0; i < res.result.records.length; i++) {
    //       let data = {
    //         title: res.result.records[i].suppilerName,
    //         value: res.result.records[i].id,
    //       };
    //       this.supplierList.push(data);
    //     }
    //   });
    // },

    //收发类别列表
    shoufaleibieListmethod(queryPath = "") {
      console.log("hfougdiuy");
      comHttp.getReceiveSendTypeListAll(queryPath).then((res) => {
        console.log("收发类别列表", res);
        this.shoufaleibieList = res.result.filter(
          (item) => item.receiveFlag === 0
        );
      });
    },
    //收发类别触发函数
    shoufaleibieMethod(value) {
      console.log("收发类别触发函数value", value);
      let array = value.split("|");
      console.log("array", array);
      // 表格自动填充所属单位
      this.form.sendReceiveTypeId = array[0]; //收发类别id
      this.form.sendReceiveType = array[1]; //收发类别name
    },
    // 生成源单号
    getOriginalNumber() {
      var date = new Date();
      // var seperator1 = "-";
      var year = date.getFullYear();
      var month = date.getMonth() + 1;
      var strDate = date.getDate();
      if (month >= 1 && month <= 9) {
        month = "0" + month;
      }
      if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
      }
      var currentdate = year + month + strDate;
      return currentdate;
      // console.log("获取源单号");
    },
    // 默认设置五行，让用户方便添加
    setColumns() {
      let size = 1;
      this.DataSource = [];

      for (let i = 0; i < size; i++) {
        let data = {
          key: i + 1,
          isNew: true,
          depotName: "", // 仓库名称
          depotNo: "", // 仓库编码
          inventoryNo: "", // 存货编码
          inventoryName: "", //  存货名称
          standardModel: "", //规格型号
          specificationsModel: "", //规格型号
          unit: "", // 单位
          quantity: "", // 	数量
          position: "", // 仓位
          coldStorageId: "", //冷库
          sourceNumber: "", // 源单单号（外键）
          giveaway: "", // 是否赠品
          remark: "", // 备注
          goodsList: [], // 物品信息列
          batchNumber: "", //批次号
          positionList: [], // 仓位列表
          coldStorageIdList: [], //冷库号
          sendReceiveType: "", // 收发类别名称
          sendReceiveTypeId: "", // 收发类别Id
          inputDate: moment().format("YYYY-MM-DD"), //入库日期
          // batchNumber: res.message,
        };
        this.DataSource.push(data);
      }
    },
    // 获取单号
    getApplyOrder() {
      let queryPath = "?string=CPRK-";
      comHttp.getOrder(queryPath).then((res) => {
        this.form.document = res.message;
      });
    },

    /**
     * @description: 所属单位（库存组织外键）
     * @param {*}
     * @return {*}
     */
    getApplyStorage() {
      this.storageList = [];
      comHttp.getAllNumberName_new_forU8c().then((res) => {
        console.log("获取所有仓库", res);
        for (let i = 0; i < res.result.length; i++) {
          let data = {
            depotName: res.result[i].storname,
            depotNo: res.result[i].storcode,
            depotId: res.result[i].pkStordoc,
          };
          this.storageList.push(data);
        }
      });
    },
    // 获取是否赠品列表
    getGiveawayList() {
      comHttp.getWarehouseGiveaway().then((res) => {
        console.log(res);
        for (let i = 0; i < res.result.length; i++) {
          let data = {
            value: parseInt(res.result[i].value),
            title: res.result[i].title,
          };
          this.giveAwayList.push(data);
        }
      });
    }, // 获取负责人列表
    getResponsiblePersonList() {
      const roleName = "仓库负责人员";
      let queryPath = "?roleName=" + roleName;
      comHttp.getUserRoleNameByUserNameId(queryPath).then((res) => {
        // console.log(res);
        for (let i = 0; i < res.result.length; i++) {
          let data = {
            userName: res.result[i].userName,
            userId: res.result[i].userId,
            workNo: res.result[i].workNo,
          };
          this.responsiblePersonList.push(data);
        }
      });
    },
    // 获取审核人
    getInspectorList() {
      const roleName = "仓库审核人员";
      let queryPath = "?roleName=" + roleName;
      comHttp.getUserRoleNameByUserNameId(queryPath).then((res) => {
        // console.log(res);
        for (let i = 0; i < res.result.length; i++) {
          let data = {
            userName: res.result[i].userName,
            userId: res.result[i].userId,
            workNo: res.result[i].workNo,
          };
          this.inspectorList.push(data);
          this.inspectorIdList.push(res.result[i].userId);
        }
        if (this.inspectorIdList.indexOf(this.$store.state.user.info.id) > -1) {
          console.log(
            "this.inspectorIdList.indexOf(this.$store.state.user.info.id) > -1",
            this.inspectorIdList.indexOf(this.$store.state.user.info.id) > -1
          );
          // 按钮状态改变:::::

          this.ExamineDisplay = false;
          console.log(this.ExamineDisplay);
        } else {
          this.ExamineDisplay = true;
        }
      });
    },
    ///END -------  生命周期函数  $$$$$

    // ------- 表单函数 ------- ;
    Submit() {
      // 单据数据
      let order_data = {
        document: this.form.document, // 单据号
        documentDate: moment(this.form.document_date).format("YYYY-MM-DD"), // 单据日期
        checkDate: moment(this.form.checkDate).format("YYYY-MM-DD"), // 审核日期

        depotId: this.form.depotId, // 仓库id
        StorageUnit: this.form.StorageUnitId, // 所属单位id
      };
      console.log("表单数据", order_data);
    },

    /**
     * @description: 新增数据 + 批量保存货架
     * @param {*}
     * @return {*}
     */
    async addNewDatatext() {
      var _DataSource = this.DataSource;

      //异步获取id
      let _data = await this.addNewData();
      console.log(_data, "返回的信息");

      console.log(_DataSource, 11111);

      //拼接数据
      var array = [];
      _DataSource.forEach((value, index) => {
        console.log(`正在执行${value}数据拼接`);
        var inOutShelf = [];
        var strs = _DataSource[index].shelves.split(",");
        strs.forEach((value) => {
          // let data = {
          //   inOutShelf: value,
          // };
          // inOutShelf.push(data);
          inOutShelf.push(value);
        });
        let xx = {
          objectId: _data[index].id, //物品id
          inOutShelf: inOutShelf, //架子号
          headId: _data[index].id, //物品id
          fosterBatchId: _DataSource[index].batchNumber, //批次号
          pkStordoc: _DataSource[index].depotId, //仓库编码
          positionId: _DataSource[index].position, //仓位
          coldStorageId: _DataSource[index].coldStorageId, //冷库号
        };
        array.push(xx);
      });

      //出入库货架批量保存接口
      cprkHttp.saveSelectShelvesByShedId(array).then((res) => {
        console.log(res);
        if (!res.success) {
          this.$message.error(res.message);
          return;
        }
        this.$message.success("货架批量保存成功");
      });
    },
    //产成品入库保存接口
    addNewData() {
      return new Promise((resolve) => {
        this.$refs.ruleForm.validate((valid) => {
          if (valid) {
            const xx = this.form;
            const _table = this.DataSource.filter(
              (item) => item.inventoryNo != ""
            );
            console.log(1111111, this.DataSource.length);
            console.log("表格物品::::", _table);
            let _xxx = _table.map((item) => {
              return {
                shelfLife: item.shelfLife, // 保质期
                // table 数据
                remarkShelf: item.shelves, //架子号
                depotId: item.depotId, // 仓库编码
                position: item.position, // 仓位
                coldStorageId: item.coldStorageId, // 冷库号
                inventoryId: item.inventoryId, // 存货编码（存货信息档案外键）
                unitPrice: item.price, // 单价
                quantity: item.actualQuantityReceived, // 数量
                actualQuantityReceived: item.actualQuantityReceived, // 实收数量
                money: Number(item.money), // 金额
                shedNo: item.recordShedId, // 棚号（外键）
                sourceNumber: item.documentNo, // 源单单号（外键）
                productionDate: item.productionDate, // 生产日期
                batchNumber: item.batchNumber, // 批次号
                storageDate: item.inputDate, // 入库日期
                remark: item.remark, // 备注
                bacteriaWarehouseCarryoverId: item.id, //!传源单下面table 的id
                contractor: xx.contractor, // 承包户
              };
            });

            let options = {
              auditMark: 2, // 审核标志, 1 已审核,2 未审核
              inOutCategoryIdentification: 2, // 入库、出库类别标识, 1-6 采购入库、产成品入库、销售出库、生产材料出库、基建出库、其他出库
              inOutIdentification: 1, // 入库、出库标识，1 入库，2 出库
              bookkeepingMark: 1, // 记账标志 , 1 已记账 , 2 未记账
              document: xx.document, // 单据号
              documentDate: xx.documentDate, // 单据日期
              sendReceiveType: (() => {
                let sendReceiveType = xx.sendReceiveType;
                if (String(Number(sendReceiveType)) == "NaN") {
                  sendReceiveType = xx.sendReceiveTypeId;
                }
                return Number(sendReceiveType);
              })(), // 收发类型
              deliveryUnit: xx.deliveryUnit, // 交货单位
              responsiblePerson: xx.responsiblePerson, // 负责人
              inspector: xx.inspector, // 审核人
              singleProducer: xx.singleProducer, // 制单人
              balance: xx.balance, // 审核日期
              pkCalbody: this.form.pkCalbody,
              pkCorp: this.form.corpId,
              cbizid: this.form.salesman, //业务员id
              warehouseObjectInformationEntities: _xxx,
            };
            console.log("[INFO] [  上传数据 ] \n", options);
            if (this.DataSource.length != 0) {
              this.checkempty(options); //校验

              if (this.empty_ === true) {
                comHttp.addInOrOutStorageOrderAndGoods(options).then((res) => {
                  if (!res.success) {
                    this.$message.error(res.message);
                    return;
                  }
                  this.$message.success("提交成功");
                  this.ResetForm(); //重置
                  // this.setColumns(); // 生成多条数据
                  resolve(res.result.list);
                  console.log("返回地信息为：", res.result.list);
                });
              }
            } else {
              this.$message.error("请添加列表信息!");
            }
          } else {
            console.log("false出现了");
          }
        });
      });
    },

    //  校验是否为空
    checkempty(option) {
      this.empty_ = true;
      console.log("11111", option);
      var message = []; //提示信息
      /*  if (this._xxx.length === 0) {
        this.empty_ = false;
        message.push("请添加列表信息!" + "\xa0\xa0\xa0");
      } */
      /* if (this.DataSource.element.length ===0) {
        this.empty_ = false;
        message.push("请添加列表信息!" + "\xa0\xa0\xa0");
      } */
      this.DataSource.forEach((element) => {
        console.log("element", element);
        if (!element.inventoryNo_dictText) {
          this.empty_ = false;
          message.push("存货信息不能为空!" + "\xa0\xa0\xa0");
        }
        if (!element.quantity || !element.actualQuantityReceived) {
          this.empty_ = false;
          message.push("存货数量不能为空!" + "\xa0\xa0\xa0");
        }
        if (!element.inventoryNo) {
          this.empty_ = false;
          message.push("仓库信息不能为空!" + "\xa0\xa0\xa0");
        }
        if (!element.inputDate) {
          this.empty_ = false;
          message.push("入库日期不能为空!" + "\xa0\xa0\xa0");
        }
      });

      if (!this.empty_) {
        this.$message.error(message);
      }
    },

    /**
     * @description: 修改数据函数
     * @param {*}
     * @return {*}
     */
    updateData() {
      // 过滤物品编码
      let newData = this.DataSource.filter((item) => item.inventoryNo != "");
      const xx = this.form;
      console.log(" --- newData ===", newData);
      console.log(" --- form ===", this.form);

      let _xxx = newData.map((item) => {
        let a = {
          shelfLife: item.shelfLife, //保质期
          remarkShelf: item.shelves, //架子号
          id: item.twoId, // id
          depotId: item.depotId, // 仓库编码
          position: item.position, // 仓位
          coldStorageId: item.coldStorageId, // 冷库号
          inventoryId: item.inventoryId, // 存货编码（存货信息档案外键）
          unitPrice: item.price, // 单价
          quantity: item.quantity, // 数量
          actualQuantityReceived: item.actualQuantityReceived, // 实收数量
          money: Number(item.money), // 金额
          shedNo: item.recordShedId, // 棚号（外键）
          sourceNumber: item.documentNo, // 源单单号（外键）
          productionDate: item.productionDate, // 生产日期
          batchNumber: item.batchNumber, // 批次号
          storageDate: item.inputDate, // 入库日期
          remark: item.remark, // 备注

          // 公共数据
          // depotId: Number(xx.depotId), // 仓库名称
          // storageUnit: item.storageUnit, // 所属单位
          contractor: xx.contractor, // 承包户
        };

        if (item.shelfLife) {
          a.shelfLife = item.shelfLife;
        }

        if (String(Number(item.position)) !== "NaN") {
          a.position = item.position;
        }

        if (String(Number(item.coldStorageId)) !== "NaN") {
          a.coldStorageId = item.coldStorageId; // 冷库
        }

        return a;
      });

      let option = {
        auditMark: 2, // 审核标志, 1 已审核,2 未审核
        bookkeepingMark: 1, // 记账标志 , 1 已记账 , 2 未记账
        id: xx.id,
        inOutCategoryIdentification: 2, // 入库、出库类别标识, 1-6 采购入库、产成品入库、销售出库、生产材料出库、基建出库、其他出库
        inOutIdentification: 1, // 入库、出库标识，1 入库，2 出库

        document: xx.document, // 单据号
        documentDate: xx.documentDate, // 单据日期
        deliveryUnit: xx.deliveryUnit, // 交货单位
        responsiblePerson: xx.responsiblePerson, // 负责人
        inspector: xx.inspector, // 审核人
        singleProducer: xx.singleProducer, // 制单人
        balance: xx.documentDate, // 审核日期

        pkCalbody: xx.pkCalbody,
        pkCorp: xx.corpId,
        cbizid: xx.salesman, //业务员id
        // -------------------- // ---------------------- //
        sendReceiveType: (() => {
          let sendReceiveType = this.form.sendReceiveType;
          if (String(Number(sendReceiveType)) == "NaN") {
            sendReceiveType = this.form.sendReceiveTypeId;
          }
          return Number(sendReceiveType);
        })(), // 收发类型
        warehouseObjectInformationEntities: _xxx,
      };

      // console.log("okokokok---------:",option);

      comHttp.updateInOrOutStorageOrderAndGoods(option).then((res) => {
        if (!res.message) {
          this.$message.error("更新失败 请重新检查数据");
          return;
        }
        this.$message.success("更新成功");
      });
    },

    /**
     * @description: 保存按钮的点击事件
     * @param {*}
     * @return {*}
     */
    handleSaveButton() {
      if (this.editOrAdd === "edit") {
        // console.log(" --- 触发更新 ---");
        this.updateData();
        return;
      }
      if (this.form.document !== "") {
        this.addNewDatatext();
      } else {
        this.$message.error("未获取到单据号,请刷新页面重试");
      }
    },

    // 新增数据,新增表单数据和物品数据

    // 物品新增
    goodsAddDataSource(newDataSource, otherId) {
      let newData = this.DataSource.filter((item) => item.inventoryNo != "");
      let array = [];
      for (let i = 0; i < newDataSource.length; i++) {
        let data = {
          otherId: otherId, // 表一id
          depotId: newData[i].depotId, // 	仓库编码（库存组织外键）
          // 库位
          position: newData[i].position, // 仓位
          coldStorageId: newData[i].coldStorageId, // 冷库号
          // 所属单位
          inventoryId: newData[i].inventoryId, // 存货编码（存货信息档案外键）
          // auxiliaryUnit: newData[i].auxiliaryUnitId, // 辅助单位
          quantity: newDataSource[i].quantity, // 	数量
          sourceNumber: newData[i].sourceNumber, // 源单单号（外键）
          batchNumber: newData[i].batchNumber, // 批次号
          giveaway: newDataSource[i].giveaway, // 是否赠品
          //deliveryDate: newDataSource[i].deliveryDate, // 出库日期
          remark: newDataSource[i].remark, // 备注
        };
        array.push(data);
      }
      // console.log("新增数据:::::", array);
      cprkHttp.InOrOutStorageGoods(array).then((res) => {
        if (res.code == 200) {
          this.$message.success("修改成功");
        } else {
          this.$message.error("修改失败");
        }
      });
    },
    // !物品修改没写
    goodsUpdateDataSource(updateDataSource) {
      let array = [];
      for (let i = 0; i < updateDataSource.length; i++) {
        let data = {
          id: updateDataSource[i].id, // 主键Id
          otherId: updateDataSource[i].otherId, // 表一id
          // depotId: newData[i].depotId, // 	仓库编码（库存组织外键）
          // 库位
          // position: newData[i].position, // 仓位
          // 所属单位
          // inventoryId: newData[i].inventoryId, // 存货编码（存货信息档案外键）
          // auxiliaryUnit: newData[i].auxiliaryUnitId, // 辅助单位
          quantity: updateDataSource[i].quantity, // 	数量
          // sourceNumber: newData[i].sourceNumber, // 源单单号（外键）
          // batchNumber: newData[i].batchNumber, // 批次号
          // giveaway: updateDataSource[i].giveaway, // 是否赠品
          deliveryDate: updateDataSource[i].deliveryDate, // 出库日期
          remark: updateDataSource[i].remark, // 备注
        };
        array.push(data);
      }
      // console.log("更新数据:::::", array);
      cprkHttp.updateInOrOutStorageGoods(array).then((res) => {
        if (res.code == 200) {
          this.$message.success("修改成功");
        } else {
          this.$message.error("修改失败");
        }
      });
    },
    //TODO:
    // 获取源单数据
    getOriginData(data) {
      //默认库存组织为七河生物
      this.$set(this.form, "bodyname", "1001F3100000000002LS|山东七河生物");
      // console.log("接收到的源单数据：：：：", data);

      data.forEach((item, index) => {
        item.key = index + 1;
        item.batchNumber = this.todayBatchNumber;
        item.inventoryId = item.inventoryNo;
        item.inventoryName = item.inventoryNoViaName_dictText; //存货名称
        item.specificationsModel = item.specification; //规格型号
        item.recordShedId_dictText = item.recordShedNumber; //棚号
        // item.quantity = item.transferOutQuantity; //数量
        this.$set(item, "quantity", item.transferOutQuantity); //数量
        item.inventoryNo = item.inventoryNo_dictText;
        //设置入库日期的默认值
        this.$set(item, "inputDate", moment().format("YYYY-MM-DD"));
      });
      //todo 合计物品数量合计
      this.mountall = 0;
      for (let i = 0; i < data.length; i++) {
        console.log(data[i].quantity, 11);
        this.mountall += data[i].quantity;
        console.log(" this.mountall", this.mountall);
      }

      this.DataSource = data;
      for (let i = 0; i < this.DataSource.length; i++) {
        this.DataSource[i].unit = data[i].unit_dictText;
      }

      let a = true;
      if (a) return;

      let newData = this.DataSource.filter((item) => item.depotNo != "");

      this.DataSource = [];
      this.DataSource = newData;
      // console.log(data);
      let lengthTemp = this.DataSource.length + 1;
      console.log("获取源单数据出发后，显示目前数据的长度+1", lengthTemp);
      //  this.form.deptId = data[0].applicationDept;
      // this.form.applicationDept = data[0].applicationDept_text;

      for (let i = 0; i < data.length; i++) {
        let data1 = {
          key: lengthTemp,
          inventoryNo: data[i].inventoryNo, //存货编码
          productDate: data[i].productDate, //生产日期
          standardModel: data[i].specificationsModel, //规格型号
          unit: data[i].unit, //单位
        };

        let temp = data1.depotId;
        this.positionList = []; //清空仓位库位下拉框
        this.coldStorageIdList = []; //清空冷库号下拉框
        this.getKuWeiList(temp);
        // console.log("this.positionList", this.positionList);
        data1.positionList = this.positionList;
        data1.coldStorageIdList = this.coldStorageIdList;
        this.DataSource.push(data1);
        // console.log("this.DataSource", this.DataSource);
        // this.DataSource[lengthTemp].key = lengthTemp;
        // this.DataSource[lengthTemp].inventoryNo = data[i].inventoryNo; //存货编码
        lengthTemp++;
      }
    },
    getOriginData2(data) {
      // console.log("从根据源单生成传进来的源单号数据", data[0].documentNo);
      this.DataSource.forEach((item) => {
        this.$set(item, "documentNo", data[0].documentNo);
      });
    },
    // 审核函数
    Examine() {
      // this.form.balance = moment().format("YYYY-MM-DD");
      this.$message.success("审核成功");
    },
    // 设置负责人id
    setResponsible_person(value, options) {
      let array = value.split("|");
      this.form.responsiblePerson = array[1];
      this.form.responsiblePersonId = options.key;
    },

    // 获取路由参数
    getRouterParam() {
      // console.log("查询参数:::", this.$route.query.Id);
      // 通过出入库id 查询出入库信息
      if (typeof this.$route.query.Id == "undefined") {
        console.log("常规跳转");
      } else {
        this.setInitInfo(this.$route.query.Id);
      }
    },

    // 通过路由跳转，设置初始化信息
    setInitInfo(id) {
      cprkHttp.getInStorageInfoById("?id=" + id).then((res) => {
        // console.log("获取所有信息::::", res);
        this.otherId = res.result.list[0].otherId; // 表一 Id
        this.form = {
          document: res.result.list[0].document,
          document_date: res.result.list[0].documentDate,
          department: res.result.list[0].deptId,
          // deptId: res.result.list[0].deptId, // 销售部门Id

          // 客户
          // 收发类别
          responsiblePerson: res.result.list[0].responsiblePerson, // 负责人
          inspector: res.result.list[0].inspector_dictText, // 审核人
          // 审核日期
          sendReceiveType: res.result.list[0].sendReceiveType_dictText, // 收发类别
          responsiblePersonId: res.result.list[0].responsiblePerson,
          inspectorId: res.result.list[0].inspector,
          singleProducer: res.result.list[0].singleProducer_dictText, // 制单人
          singleProducerId: res.result.list[0].singleProducer,
        };

        // console.log("表头信息:::::", this.form);
        let array = [];
        for (let i = 0; i < res.result.list.length; i++) {
          // console.log("表格信息:::::", 123);

          let data = {
            key: i + 1,
            id: res.result.list[i].twoId,
            otherId: res.result.list[i].otherId,
            isNew: false,
            depotNo: res.result.list[i].depotId, // 仓库编码
            depotName: res.result.list[i].depotId_dictText, // 仓库名称
            // 库位
            position: res.result.list[i].position, // 仓位
            coldStorageId: res.result.list[i].coldStorageId_dictText, // 所属单位
            inventoryNo: res.result.list[i].StorageUnit, // 存货编码
            inventoryName: res.result.list[i].inventoryId_dictText, // 存货名称
            standardModel: res.result.list[i].standardModel, // 规格型号
            unit: res.result.list[i].unit, // 单位
            // auxiliaryUnit: res.result.list[i].auxiliaryUnit, // 辅助单位
            quantity: res.result.list[i].quantity, // 数量
            sourceNumber: res.result.list[i].sourceNumber, // 源单单号
            batchNumber: res.result.list[i].batchNumber, // 批次号
            giveaway: res.result.list[i].giveaway_dictText, // 是否赠品
            storageDate: res.result.list[i].storageDate, // 出库日期
            remark: res.result.list[i].remark, // 备注
            goodsList: this.getGoodSInfo(res.result.list[i].depotId),
          };
          array.push(data);
        }
        this.DataSource = array;
        // console.log("表格信息:::", this.DataSource);
        this.UpdateTmp = false;
      });
    },

    // 表格添加新的一条记录
    newMember() {
      this.DataSource.push({
        key: this.DataSource.length + 1,
        batchNumber: this.todayBatchNumber,
        // ---------------------------- //
        isNew: true,
        depotName: "", // 仓库名称
        depotNo: "", // 仓库编码
        inventoryNo: "", // 存货编码
        inventoryName: "", //  存货名称
        standardModel: "", //规格型号
        unit: "", // 单位
        quantity: "", // 	数量
        actualQuantityReceived: "", //实收数量
        position: "", // 仓位
        coldStorageId: "", //冷库号
        sourceNumber: "", // 源单单号（外键）
        giveaway: "", // 是否赠品
        remark: "", // 备注
        goodsList: [], // 物品信息列
        positionList: [], // 仓位列表
        coldStorageIdList: [], //冷库列表
        inputDate: moment().format("YYYY-MM-DD"), //入库日期
        specificationsModel: "", //规格
        specificationsModel_dictText: "", //规格
      });
    },
    // 设置审核人id
    setInspector(value, options) {
      let array = value.split("|");
      this.form.inspector = array[1];
      this.form.inspectorId = options.key;
    },

    /**
     * @description: 获取物品信息
     * @param {*} id
     * @return {*}
     */
    getGoodSInfo2(target, id) {
      comHttp.getInventoryInformation("?depotNo=" + id).then((res) => {
        let result = res.result;
        result.map((item) => {
          item.inventoryId = item.id;
          item.standardModel = item.specificationsModel;
        });
        target.goodsList = result;
        console.log("[INFO] [获取存货信息] \n", result);
      });
    },

    /**
     * @description: 获取仓位列表
     * @param {*} id
     * @return {*}
     */
    getPositionListById(target, depotId) {
      console.log("target", target);

      //清空仓位
      let array = [];
      this.$set(target, "positionList", array);

      comHttp
        .getPositionInformationListByDepotId("?id=" + depotId)
        .then((res) => {
          console.log("---------------- 【获取仓位列表】 -------------");
          console.log(res);

          if (res.result[0].children) {
            //解决仓位信息缓存
            let resetRes = res.result[0].children;
            const disableParent = (Tree) => {
              Tree.forEach((item) => {
                console.log(item, "111");
                if (item.children.length != 0) {
                  item[`disabled`] = true;
                } else {
                  disableParent(item.children);
                }
              });
            };

            disableParent(resetRes);

            this.$set(target, "positionList", resetRes);
          } else {
            let nosome = [];
            this.$set(target, "positionList", nosome);
          }
        });
    },
    getcoldStorageIdList(target, depotId) {
      console.log("target", target);

      //清空仓位
      let array = [];
      this.$set(target, "coldStorageIdList", array);

      comHttp
        .getPositionInformationListByDepotId("?id=" + depotId)
        .then((res) => {
          console.log("---------------- 【获取冷库列表】 -------------");
          console.log(res);

          if (res.result[0].children) {
            //解决仓位信息缓存
            let resetRes = res.result[0].children;
            const disableParent = (Tree) => {
              Tree.forEach((item) => {
                console.log(item, "冷库列表");
              });
            };

            disableParent(resetRes);

            this.$set(target, "coldStorageIdList", resetRes);
          } else {
            let nosome = [];
            this.$set(target, "coldStorageIdList", nosome);
          }
        });
    },
    // 获取物品信息
    getGoodSInfo(id) {
      /* let goodsList = [];
      comHttp.getInventoryInformation("?depotNo=" + id).then((res) => {
        console.log("--- 获取存货信息 --- before ---", res);
        for (let i = 0; i < res.result.length; i++) {
          let data = {
            inventoryId: res.result[i].id, // 存货 id
            inventoryName: res.result[i].inventoryName,
            inventoryNo: res.result[i].inventoryNo,
            standardModel: res.result[i].specificationsModel,
            unit: res.result[i].unit,
          };
          goodsList.push(data);
        }
        console.log("--- 获取存货信息 --- after ---", goodsList);
      });
      return goodsList; */
      return new Promise((resolve) => {
        comHttp.getInventoryInformation("?depotNo=" + id).then((res) => {
          let result = res.result;
          result.map((item) => {
            item.inventoryId = item.id;
            item.standardModel = item.specificationsModel;
          });
          resolve(result);
        });
      });
    },
    // 提交物品信息
    submitGoodsData(other_id) {
      console.log("表一id:::", other_id);
      console.log("数据", this.DataSource);
      // 筛选出表格数据中存货编码为空的数据!!!!!, 这些数据不能提交
      const newData = this.DataSource.filter((item) => item.inventoryNo != "");
      console.log(newData);
      let goods_data = [];
      for (let i = 0; i < newData.length; i++) {
        let data = {
          otherId: other_id, // 表一id
          depotId: newData[i].depotId, // 	仓库编码（库存组织外键）
          position: newData[i].position, // 仓位
          coldStorageId: newData[i].coldStorageId, // 冷库号
          // 所属单位
          inventoryId: newData[i].inventoryId, // 存货编码（存货信息档案外键）
          // auxiliaryUnit: newData[i].auxiliaryUnitId, // 辅助单位
          quantity: newData[i].quantity, // 	数量
          sourceNumber: newData[i].sourceNumber, // 源单号（外键）
          batchNumber: newData[i].batchNumber, // 批次号
          giveaway: newData[i].giveaway, // 是否赠品
          storageDate: moment(newData[i].storageDate).format("YYYY-MM-DD"), // 入库日期
          remark: newData[i].remark, // 备注
          depotLocation: newData[i].depotLocation, // 库位
          // moment(this.form.sort).format("YYYY-MM-DD"), // 制单日期
          // contractor: "", // 承包户（外键）
          // currency: "", // 币种
          // currencyAmount: 0, // 本币金额
          // deduction: 0, // 扣重
          // deptId: "", //	 部门编码（外键）
          // expectedNo: "", // 预期号
          // farmers: "", // 农户（外键）
          // finishedProductType: "", // 产成品分类
          // id: 0,
          // money: 0, // 金额
          // originalCurrency: 0, // 原币金额
          // productionDate: "", // 	生产日期
          // receivingDepot: 0, //  收料仓库（外键）
          // shedNo: 0, // 棚号（外键）
          // shelfLife: "", // 保质期(月)
          // storageDate: "", // 	入库日期
          // storageUnit: 0, // 存储单位（库存组织外键）
          // supplier: "", // 供应商
          // unitPrice: 0, // 单价
        };
        goods_data.push(data);
      }
      console.log("下方表格数据::::", goods_data);
      cprkHttp.InOrOutStorageGoods(goods_data).then((res) => {
        console.log(res);
        if (res.code == 200) {
          this.$message.success("提交成功");
        } else {
          this.$message.error("提交失败");
        }
      });
    },

    ///END -------  表单函数  $$$$$

    // 获取批次号
    // getBatchNumberList(id) {
    //   comHttp.getBatchNumberList("?inventoryId=" + id).then((res) => {
    //     console.log(res);
    //   });
    // },

    // 表单仓库点击按钮
    setdataSourceDepartment(value, option) {
      let array = value.split("|");
      console.log(array[0]);
      this.form.depotName = array[1];
      let key = option.key;
      // 获取物品信息列表,根据仓库编码
      let goodsList = this.getGoodSInfo(key);
      let TempList = this.setGoodsList(key);
      let coldStorageIdList = this.getcoldStorageIdList(key);

      console.log("let TempList", TempList);

      // 根据仓库查询物品信息,并存储到相应的物品信息表中
      for (let i = 0; i < this.DataSource.length; i++) {
        this.DataSource[i].depotNo = array[0];
        this.DataSource[i].depotName = array[1];
        this.DataSource[i].depotId = key;
        this.DataSource[i].goodsList = goodsList;
        this.DataSource[i].positionList = TempList;
        this.DataSource[i].coldStorageIdList = coldStorageIdList;
        // console.log("for循环中的数据", this.DataSource);
      }
      console.log("通过ID获取仓位:::::", this.DataSource);
    },
    // 设置所属单位, 上面表单触发事件
    setdataSourceStorageUnit(value, option) {
      let array = value.split("|");
      this.form.storageUnit = array[1];
      // console.log(array[0]);
      let key = option.key;
      for (let i = 0; i < this.DataSource.length; i++) {
        this.DataSource[i].StorageUnitNo = array[0];
        this.DataSource[i].StorageUnit = array[1];
        this.DataSource[i].StorageUnitId = key;
      }
    },

    /**
     * @description: 获取存货编码
     * @param {*} key
     * @return {*}
     */
    inventoryNoSelectChange(record, val) {
      // item.inventoryId +
      // '|' +
      // item.inventoryNo +
      // '|' +
      // item.inventoryName

      console.log(record);
      console.log(val);
      let key = 1;

      let a = true;
      if (a) return;
      let target = this.DataSource.filter((item) => item.key === key)[0];
      // 分割字符串,取出来存货编码
      let array = target.inventoryNo.split("|");
      target.inventoryId = array[0]; // 赋值给存货编码
      target.inventoryNo = array[1]; // 赋值给存货编码
      target.inventoryName = array[2]; // 赋值给存货名称
      target.inventoryName_dictText = array[2]; // 赋值给存货名称

      let goodsInfomation = target.goodsList.filter(
        (item) => (item.inventoryId = array[0])
      )[0];
      // console.log("物品信息::::", goodsInfomation);
      target.inventoryId = goodsInfomation.inventoryId;
      target.specificationsModel_dictText = goodsInfomation.standardModel;
      target.unit = goodsInfomation.unit;

      // target.BatchList = this.getBatchNumberList(goodsInfomation.inventoryId); // 获取批次列表
    },

    /**
     * @description: 设置存货列表
     * @param {*}
     * @return {*}
     */

    async setGoodsList(key) {
      let target = this.DataSource.filter((item) => item.key === key)[0];
      let array = target.depotNo.split("|");
      target.depotNo = array[0]; // 仓库id
      target.depotName = array[1]; // 仓库名称

      let SotrageInfo = this.storageList.filter(
        (item) => item.depotNo === array[0]
      )[0];
      target.depotId = SotrageInfo.depotId;

      console.log("--- target.depotId ---", target.depotId);

      let goodsList = this.getGoodSInfo(target.depotId);
      target.goodsList = goodsList;

      this.getPositionListById(target, SotrageInfo.depotId); // 获取仓位信息
      this.getcoldStorageIdList(target, SotrageInfo.depotId); // 获取仓位信息
    },

    // 获取所属单位,表格触发事件
    storageUnitSelectChange(key) {
      let target = this.DataSource.filter((item) => item.key === key)[0];
      let array = target.StorageUnit.split("|");
      target.StorageUnitNo = array[0]; // 仓库id
      target.StorageUnit = array[1]; // 仓库名称

      let SotrageInfo = this.storageList.filter(
        (item) => item.depotNo === array[0]
      )[0];
      target.StorageUnitId = SotrageInfo.depotId;
    },
    // 禁用父节点
    disableParent(Tree) {
      return new Promise((resolve) => {
        Tree.forEach((item) => {
          console.log(item);
          if (item.children.length != 0) {
            item[`disabled`] = true;
          } else {
            this.disableParent(item.children);
          }
        });
        resolve(Tree);
      });
    },

    // ------- 主页面表格删除一行 ------- ;
    cancle(key) {
      // console.log(key);
      if (this.DataSource.length > 1) {
        this.DataSource.splice(key - 1, 1);
        //序号重新排序
        for (let i = 0; i < this.DataSource.length; i++) {
          this.DataSource[i].key = i + 1;
        }
        this.$message.success("取消成功");
      } else {
        this.$message.error("至少保留一行");
      }
    },

    // 获取仓位列表
    getPositionList(id) {
      let positionList = [];
      return new Promise((resolve) => {
        comHttp.getPositionInformationListByDepotId("?id=" + id).then((res) => {
          console.log("----- 根据ID获取仓位列表res -----", res);
          console.log("----- id -----", id);

          positionList = res.result[0].children;
          resolve(positionList);
        });
      });
    },
    getKuWeiList(id) {
      console.log("进入getKuWeiList");
      comHttp.getPositionInformationListByDepotId("?id=" + id).then((res) => {
        this.positionList = res.result[0].children;
        console.log("res", res);
      });
    },

    // --- 获取当天批次号 ---
    getTodayBatchNumber() {
      cprkHttp.getBatchNumber().then((res) => {
        // 自动生成批次号
        this.todayBatchNumber = res.message;
      });
    },

    // 重置
    Reset() {
      this.form = {
        document_date: "", // 日期
        sendReceiveType: "", // 收发类别
        storageId: "", // 申请仓库名称
        storageName: "", // 仓库名称名称
        departmentNo: "", // 部门编号
        department: "", // 部门
      };
      this.DataSource = [];
      // this.setColumns();
    },

    getWarehouseInfo(value) {
      let array = value.split("|");
      this.form.depotName = array[1]; // 赋值给仓库名称名称
    },
    //获取单位信息
    getDepartmentInfo(value) {
      let array = value.split("|");
      this.form.depart = array[1]; //
    },
    main_Submit() {
      console.log("123");
      console.log("表格数据:::", this.DataSource);

      // 筛选出表格数据中存货编码为空的数据!!!!!, 这些数据不能提交
      const newData = this.DataSource.filter(
        (item) => typeof item.inventory_Id != "undefined"
      );
      console.log("表格数据:::", newData);
    },
    handleSearch() {
      console.log("---- handlereset ----");
    },
    onSubmit() {
      console.log("---- onsubmit ----");
    },
    output() {
      console.log("---- output ----");
    },

    // 添加物品入库按钮事件
    addgoods_showModal() {
      // 添加物品入库按钮，点击显示
      this.visible = true;
    },
    // 添加物品入库按钮后显示的表单，点击确认
    addgoods_Ok(e) {
      // 把数据发送到后端去

      this.confirmLoading = true;
      console.log(e);

      setTimeout(() => {
        this.visible = false;
        this.confirmLoading = false;
      }, 2000);
    },
    // 添加物品入库按钮后显示的表单，点击取消
    addgoods_Cancel(e) {
      console.log(e);
      console.log("Clicked cancel button");
      this.visible = false;
    },
    // 结束

    //保存重置表单
    ResetForm() {
      this.form = {
        document: "", // 单据号
        documentDate: moment().format("YYYY-MM-DD"), // 单据日期
        depotId: "", // 仓库名称
        depotName: "",
        // storageUnit: "", // 所属单位
        // storageUnitName: "",
        sendReceiveType: "", // 收发类别
        sendReceiveTypeName: "",
        deliveryUnit: "", // 交货单位
        deliveryUnitName: "",
        contractorName: "", // 承包户
        contractor: "",
        responsiblePerson: "", // 负责人
        responsiblePersonName: "",
        inspectorName: "", // 审核人
        inspector: "",
        balance: moment().format("YYYY-MM-DD"), // 审核日期
        singleProducerName: this.$store.state.user.info.username, // 制单人
        singleProducer: this.$store.state.user.info.id, // 制单人Id
      };
      this.DataSource = []; //tanble重置
      this.mountall = 0; //合计物品数量重置
      this.getApplyOrder(); // 获取单据号
    },

    //! 反审核功能
    Auditfunction() {
      // 过滤物品编码
      let newData = this.DataSource.filter((item) => item.inventoryNo != "");
      let form = this.form;
      const xx = this.form;
      console.log(" --- newData ===", newData);
      console.log(" --- form ===", form);

      let _xxx = newData.map((item) => {
        let a = {
          id: item.twoId, // id
          depotId: item.depotId, // 仓库编码
          position: item.position, // 仓位
          coldStorageId: item.coldStorageId, // 库位
          inventoryId: item.inventoryId, // 存货编码（存货信息档案外键）
          unitPrice: item.price, // 单价
          quantity: item.quantity, // 数量
          money: Number(item.money), // 金额
          shedNo: item.recordShedId, // 棚号（外键）
          sourceNumber: item.documentNo, // 源单单号（外键）
          productionDate: item.productionDate, // 生产日期
          batchNumber: item.batchNumber, // 批次号
          storageDate: item.inputDate, // 入库日期
          remark: item.remark, // 备注

          // 公共数据
          // depotId: Number(xx.depotId), // 仓库名称
          // storageUnit: item.storageUnit, // 所属单位
          contractor: xx.contractor, // 承包户
        };

        if (item.shelfLife) {
          a.shelfLife = item.shelfLife;
        }

        if (String(Number(item.position)) !== "NaN") {
          a.position = item.position;
        }

        if (String(Number(item.coldStorageId)) !== "NaN") {
          a.coldStorageId = item.coldStorageId; // 库位
        }

        return a;
      });

      let option = {
        id: xx.id,
        auditMark: 2, // 审核标志, 1 已审核,2 未审核
        bookkeepingMark: 1, // 记账标志 , 1 已记账 , 2 未记账
        // id: form.id,
        inOutCategoryIdentification: 2, // 入库、出库类别标识, 1-6 采购入库、产成品入库、销售出库、生产材料出库、基建出库、其他出库
        inOutIdentification: 1, // 入库、出库标识，1 入库，2 出库

        document: xx.document, // 单据号
        documentDate: xx.documentDate, // 单据日期
        deliveryUnit: xx.deliveryUnit, // 交货单位
        responsiblePerson: xx.responsiblePerson, // 负责人
        inspector: xx.inspector, // 审核人
        singleProducer: xx.singleProducer, // 制单人
        balance: xx.balance, // 审核日期

        pkCalbody: this.form.pkCalbody,
        pkCorp: this.form.corpId,
        cbizid: this.form.salesman, //业务员id
        // -------------------- // ---------------------- //
        sendReceiveType: (() => {
          let sendReceiveType = xx.sendReceiveType;
          if (String(Number(sendReceiveType)) == "NaN") {
            sendReceiveType = xx.sendReceiveTypeId;
          }
          return Number(sendReceiveType);
        })(), // 收发类型
        warehouseObjectInformationEntities: _xxx,
      };

      console.log(option);

      comHttp.updateInOrOutStorageOrderAndGoods(option).then((res) => {
        if (!res.message) {
          this.$message.error("审核失败 请重新检查数据");
          return;
        }
        this.$message.success("审核成功");
        //标志位修改
        this.postSynchronized("未同步");
        this.update_audit("未反审核");
        this.update_Mark(1);

        // 跳转回列表页面
        this.$router.push("/ProductInputList");
      });
    },
    //! 是否同步标志位
    postSynchronized(isOrNo) {
      let data = {
        id: this.form.id,
        isSynchronized: isOrNo,
      };
      comHttp.updateInOrOutStorageOrder(data).then((res) => {
        console.log(res);
      });
    },
    //是否反审核标志位
    update_audit(isOrNo) {
      let data = {
        id: this.form.id,
        isAntiAudit: isOrNo,
      };
      comHttp.updateInOrOutStorageOrder(data).then((res) => {
        console.log(res);
      });
    },
    //审核标志位
    update_Mark(isOrNo) {
      let data = {
        id: this.form.id,
        auditMark: isOrNo,
      };
      comHttp.updateInOrOutStorageOrder(data).then((res) => {
        console.log(res);
      });
    },
  },
};
</script>

<style>
</style>